<template>
	<view class="mine-page">
		<!-- 用户信息区域 -->
		<view class="user-section">
			<view class="user-info">
				<image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
				<view class="user-details">
					<view class="nickname-row">
						<text class="nickname">{{ userInfo.nickname }}</text>
						<view class="verify-badge" @click="goVerify" v-if="!userInfo.isVerified">
							<text class="verify-text">未实名，立即认证</text>
						</view>
					</view>
					<view class="progress-row">
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: userInfo.profileProgress + '%' }"></view>
						</view>
						<text class="progress-text" @click="goCompleteProfile">完善资料 ></text>
					</view>
				</view>
			</view>

			<!-- 数据统计 -->
			<view class="stats-row">
				<view class="stat-item" @click="goToPage('myConnection')">
					<text class="stat-number">{{ stats.myConnection }}</text>
					<text class="stat-label">我的牵线</text>
				</view>
				<view class="stat-item" @click="goToPage('myFavorites')">
					<text class="stat-number">{{ stats.myFavorites }}</text>
					<text class="stat-label">我的收藏</text>
				</view>
				<view class="stat-item" @click="goToPage('whoViewedMe')">
					<text class="stat-number">{{ stats.whoViewedMe }}</text>
					<text class="stat-label">谁看过我</text>
				</view>
				<view class="stat-item" @click="goToPage('iViewed')">
					<text class="stat-number">{{ stats.iViewed }}</text>
					<text class="stat-label">我看过谁</text>
				</view>
			</view>
		</view>

		<!-- VIP会员卡片 -->
		<view class="vip-card" @click="goVip" v-if="!userInfo.isVip">
			<view class="vip-content">
				<view class="vip-icon">👑</view>
				<view class="vip-info">
					<text class="vip-title">VIP会员未开通</text>
					<text class="vip-subtitle">开通会员可享受尊贵服务哦</text>
				</view>
			</view>
			<view class="vip-button">立即开通</view>
		</view>

	<!-- 专属红娘（仅登录后显示） -->
	<view class="matchmaker-card" v-if="currentUserId">
		<text class="matchmaker-text">您的专属红娘：{{ matchmaker.code || '暂无' }} {{ matchmaker.phone || '' }}</text>
	</view>

		<!-- 快捷入口 -->
		<view class="quick-actions">
			<view class="action-item" @click="showCheckinPopup">
				<view class="action-icon calendar-icon">📅</view>
				<text class="action-label">签到</text>
			</view>
			<view class="action-item" @click="goToPage('customize')">
				<view class="action-icon phone-icon">📞</view>
				<text class="action-label">私人定制</text>
			</view>
			<view class="action-item" @click="goToPage('matchmakers')">
				<view class="action-icon heart-icon">❤️</view>
				<text class="action-label">红娘服务</text>
			</view>
		</view>

		<!-- 签到弹窗 -->
		<uni-popup ref="checkinPopup" type="center" :mask-click="true">
			<view class="checkin-popup">
				<view class="popup-header">
					<text class="popup-title">每日签到</text>
					<view class="close-btn" @click="closeCheckinPopup">
						<text class="close-icon">✕</text>
					</view>
				</view>

				<view class="checkin-info">
					<view class="info-item">
						<text class="info-label">已连续签到</text>
						<text class="info-value">{{ checkinData.continuousDays }} 天</text>
					</view>
					<view class="info-item">
						<text class="info-label">累计签到</text>
						<text class="info-value">{{ checkinData.totalDays }} 天</text>
					</view>
				</view>

				<scroll-view scroll-y class="checkin-content">
					<view class="checkin-calendar">
						<view class="calendar-header">
							<text class="month-text">{{ currentMonth }}</text>
						</view>
						<view class="week-header">
							<text class="week-day" v-for="day in weekDays" :key="day">{{ day }}</text>
						</view>
						<view class="calendar-body">
							<view 
								class="calendar-day" 
								v-for="(day, index) in calendarDays" 
								:key="index"
								:class="{
									'empty': !day.date,
									'checked': day.checked,
									'today': day.isToday
								}"
							>
								<text class="day-num" v-if="day.date">{{ day.date }}</text>
								<view class="check-mark" v-if="day.checked">✓</view>
							</view>
						</view>
					</view>

					<view class="checkin-rewards">
						<text class="rewards-title">签到奖励</text>
						<view class="rewards-list">
							<view 
								class="reward-item" 
								v-for="(reward, index) in checkinRewards" 
								:key="index"
								:class="{ 'received': reward.received, 'current': reward.isCurrent }"
							>
								<view class="reward-icon">{{ reward.icon }}</view>
								<text class="reward-day">第{{ reward.day }}天</text>
								<text class="reward-text">{{ reward.reward }}</text>
								<view class="received-mark" v-if="reward.received">✓</view>
							</view>
						</view>
					</view>
				</scroll-view>

				<view class="checkin-button-wrapper">
					<button 
						class="checkin-btn" 
						:class="{ 'disabled': checkinData.todayChecked }" 
						@click="handleCheckin"
						:disabled="checkinData.todayChecked"
					>
						{{ checkinData.todayChecked ? '今日已签到' : '立即签到' }}
					</button>
				</view>
			</view>
		</uni-popup>

		<!-- 功能菜单列表 -->
		<view class="menu-list">
			<view class="menu-item" @click="goToPage('basicInfo')">
				<view class="menu-left">
					<text class="menu-icon">🆔</text>
					<text class="menu-text">基本资料</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
			<view class="menu-item" @click="goToPage('partnerRequirement')">
				<view class="menu-left">
					<text class="menu-icon">💜</text>
					<text class="menu-text">对象要求</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
			<view class="menu-item" @click="goToPage('blacklist')">
				<view class="menu-left">
					<text class="menu-icon">📋</text>
					<text class="menu-text">黑名单</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
			<view class="menu-item" @click="goToPage('myActivity')">
				<view class="menu-left">
					<text class="menu-icon">📷</text>
					<text class="menu-text">我的活动</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
			<view class="menu-item" @click="goToPage('partTimeMatchmaker')">
				<view class="menu-left">
					<text class="menu-icon">💎</text>
					<text class="menu-text">兼职红娘</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
			<view class="menu-item" @click="goToPage('settings')">
				<view class="menu-left">
					<text class="menu-icon">⚙️</text>
					<text class="menu-text">设置</text>
				</view>
				<text class="menu-arrow">›</text>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<view class="tabbar">
			<view class="tabbar-item" @click="switchTab('index')">
				<text class="tabbar-icon">🏠</text>
				<text class="tabbar-text">首页</text>
			</view>
			<view class="tabbar-item" @click="switchTab('plaza')">
				<text class="tabbar-icon">💕</text>
				<text class="tabbar-text">广场</text>
			</view>
			<view class="tabbar-item" @click="switchTab('recommend')">
				<text class="tabbar-icon">👍</text>
				<text class="tabbar-text">推荐</text>
			</view>
			<view class="tabbar-item" @click="switchTab('message')">
				<text class="tabbar-icon">💬</text>
				<text class="tabbar-text">消息</text>
			</view>
			<view class="tabbar-item active" @click="switchTab('mine')">
				<text class="tabbar-icon">👤</text>
				<text class="tabbar-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 网关地址
				gatewayURL: 'http://localhost:8083',
				
				// 用户ID（如果没有登录，默认为1）
				currentUserId: null,
				
				// 用户信息（从后端获取）
				userInfo: {
					userId: null,
					nickname: '准备加载...',
					avatar: 'https://via.placeholder.com/100',
					phone: '',
					email: '',
					gender: null,
					genderText: '未知',
					birthDate: null,
					age: null,
					isVerified: false,
					profileProgress: 0,
					isVip: false
				},
				
				stats: {
					myConnection: 0,
					myFavorites: 0,
					whoViewedMe: 0,
					iViewed: 0
				},
				matchmaker: {
					code: 'xxxxx',
					phone: '99*******99'
				},
				// 签到数据
				checkinData: {
					continuousDays: 0,
					totalDays: 0,
					todayChecked: false,
					checkedDates: []
				},
				weekDays: ['日', '一', '二', '三', '四', '五', '六'],
				currentMonth: '',
				calendarDays: [],
				checkinRewards: []
			}
		},
	onLoad() {
		console.log('=== 我的页面加载开始 ===')
		
		// 立即检查登录状态
		const token = uni.getStorageSync('token')
		const userInfo = uni.getStorageSync('userInfo')
		
		if (!token || !userInfo) {
			// 未登录，立即强制跳转到登录页
			console.log('❌ 未登录，强制跳转到登录页')
			uni.showModal({
				title: '需要登录',
				content: '请先登录后查看个人信息',
				showCancel: false,  // 不允许取消
				confirmText: '去登录',
				success: () => {
					uni.navigateTo({
						url: '/pages/page3/page3'
					})
				}
			})
			return
		}
		
		// 已登录，同步登录状态
		this.syncLoginStatus()
	},
		
	onShow() {
		console.log('=== 我的页面显示 ===')
		
		// 检查登录状态
		const token = uni.getStorageSync('token')
		const userInfo = uni.getStorageSync('userInfo')
		
		if (!token || !userInfo) {
			// 未登录，直接跳转（不显示弹窗，因为onLoad已经显示过了）
			console.log('❌ 未登录，跳转到登录页')
			uni.navigateTo({
				url: '/pages/page3/page3'
			})
			return
		}
		
		// 已登录，同步登录状态
		this.syncLoginStatus()
	},
		methods: {
		// 同步登录状态并更新页面数据
		syncLoginStatus() {
			console.log('=== 同步登录状态 ===')
			
			// 获取最新的登录信息
			const token = uni.getStorageSync('token')
			const userInfo = uni.getStorageSync('userInfo')
			const userId = uni.getStorageSync('userId')
			
			console.log('最新登录状态:')
			console.log('- token存在:', !!token)
			console.log('- userInfo存在:', !!userInfo)
			console.log('- userId:', userId)
			
			if (token && userInfo && userId) {
				// 已登录状态 - 立即使用存储的用户信息更新页面
				console.log('✅ 检测到登录状态，立即更新页面数据')
				
				this.currentUserId = parseInt(userId)
				
				// 直接使用存储的用户信息更新页面
				this.userInfo = {
					userId: userInfo.userId || userId,
					nickname: userInfo.nickname || '用户',
					avatar: userInfo.avatarUrl || userInfo.avatar || 'https://via.placeholder.com/100',
					phone: this.maskPhone(userInfo.phone) || '',
					email: userInfo.email || '',
					gender: userInfo.gender,
					genderText: this.getGenderText(userInfo.gender),
					birthDate: userInfo.birthDate,
					age: this.calculateAge(userInfo.birthDate),
					isVerified: false,
					profileProgress: 50,
					isVip: false
				}
				
				console.log('✅ 页面用户信息已更新:', this.userInfo.nickname)
				
				// 强制页面刷新
				this.$forceUpdate()
				
				// 设置统计数据
				this.stats = {
					myConnection: Math.floor(Math.random() * 8) + 2,
					myFavorites: Math.floor(Math.random() * 15) + 5,
					whoViewedMe: Math.floor(Math.random() * 12) + 3,
					iViewed: Math.floor(Math.random() * 20) + 8
				}
				
				// 延迟尝试API更新（如果服务可用）
				setTimeout(() => {
					this.loadUserInfo()
				}, 2000)
				
			} else {
				// 未登录状态 - 设置空白用户信息
				console.log('❌ 未检测到登录状态')
				this.currentUserId = null
				
				// 设置未登录状态的用户信息
				this.userInfo = {
					userId: null,
					nickname: '未登录',
					avatar: 'https://via.placeholder.com/100?text=未登录',
					phone: '',
					email: '',
					gender: 0,
					genderText: '未知',
					birthDate: null,
					age: null,
					isVerified: false,
					profileProgress: 0,
					isVip: false
				}
				
				// 清空统计数据
				this.stats = {
					myConnection: 0,
					myFavorites: 0,
					whoViewedMe: 0,
					iViewed: 0
				}
				
				// 强制页面更新
				this.$forceUpdate()
				
				// 提示需要登录
				setTimeout(() => {
					uni.showModal({
						title: '需要登录',
						content: '请先登录后查看完整功能',
						showCancel: false,
						confirmText: '去登录',
						success: () => {
							uni.navigateTo({
								url: '/pages/page3/page3'
							})
						}
					})
				}, 500)
			}
		},
			
			// 简单的手机号脱敏
			maskPhone(phone) {
				if (!phone || phone.length < 11) return phone
				return phone.substring(0, 3) + '****' + phone.substring(7)
			},
			
			// 获取性别文字
			getGenderText(gender) {
				switch(gender) {
					case 1: return '男'
					case 2: return '女'
					default: return '未知'
				}
			},
			
			// 计算年龄
			calculateAge(birthDate) {
				if (!birthDate) return null
				const birth = new Date(birthDate)
				const today = new Date()
				let age = today.getFullYear() - birth.getFullYear()
				const monthDiff = today.getMonth() - birth.getMonth()
				if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
					age--
				}
				return age
			},
		// 从后端加载用户信息（通过网关）
		loadUserInfo() {
			// 检查是否真正登录（必须有token和userInfo）
			const token = uni.getStorageSync('token')
			const userInfo = uni.getStorageSync('userInfo')
			
			if (!token || !userInfo) {
				console.warn('未登录，不加载用户信息')
				return
			}
			
			// 检查用户ID是否有效
			if (!this.currentUserId || this.currentUserId <= 0) {
				console.warn('无有效用户ID，无法加载用户信息')
				this.setDefaultUserInfo()
				return
			}
			
			console.log('加载用户信息，用户ID:', this.currentUserId)
				
				// 获取用户基本信息
				uni.request({
					url: this.gatewayURL + '/api/user/info?userId=' + this.currentUserId,
					method: 'GET',
					success: (res) => {
						console.log('用户信息API响应:', res.data)
						
						if (res.data && res.data.code === 200) {
							const data = res.data.data
							console.log('✅ API返回用户数据:', data)
							
							// 更新用户信息
							this.userInfo = {
								userId: data.userId,
								nickname: data.nickname || '用户',
								avatar: data.avatar || 'https://via.placeholder.com/100',
								phone: data.phone,
								email: data.email,
								gender: data.gender,
								genderText: data.genderText,
								birthDate: data.birthDate,
								age: data.age,
								isVerified: data.isVerified || false,
								profileProgress: data.profileProgress || 0,
								isVip: data.isVip || false,
								// 扩展信息
								height: data.height,
								weight: data.weight,
								star: data.star,
								animal: data.animal,
								educationLevel: data.educationLevel,
								educationText: data.educationText,
								schoolName: data.schoolName,
								company: data.company,
								jobTitle: data.jobTitle,
								salaryRange: data.salaryRange,
								salaryText: data.salaryText,
								maritalStatus: data.maritalStatus,
								maritalText: data.maritalText,
								house: data.house,
								houseText: data.houseText,
								car: data.car,
								carText: data.carText,
								hobby: data.hobby,
								authenticityScore: data.authenticityScore
							}
							
							console.log('✅ 用户信息更新完成:', this.userInfo.nickname)
							
							// 强制页面更新
							this.$forceUpdate()
							
							// 加载签到信息
							this.loadCheckinInfo()
						} else {
							console.error('获取用户信息失败:', res.data)
							const errorMsg = res.data?.message || '获取用户信息失败'
							
							// 如果是用户不存在的错误，给出特殊提示
							if (errorMsg.includes('用户不存在') || errorMsg.includes('用户ID无效')) {
								uni.showModal({
									title: '用户不存在',
									content: `当前用户ID（${this.currentUserId}）在数据库中不存在，登录信息有误，请重新登录`,
									showCancel: false,
									confirmText: '重新登录',
									success: () => {
										// 清除登录信息并跳转登录页
										uni.clearStorageSync()
										uni.navigateTo({
											url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/mine/index')
										})
									}
								})
							} else {
								uni.showToast({
									title: errorMsg,
									icon: 'none'
								})
								// 设置默认用户信息
								this.setDefaultUserInfo()
							}
						}
					},
					fail: (err) => {
						console.error('获取用户信息失败:', err)
						
						// API失败时，提示用户网络错误
						uni.showModal({
							title: '网络错误',
							content: '无法连接到服务器，请检查网络连接或稍后重试',
							showCancel: true,
							cancelText: '返回',
							confirmText: '重试',
							success: (modalRes) => {
								if (modalRes.confirm) {
									// 重试加载
									this.loadUserInfo()
								}
							}
						})
						
						// 设置默认用户信息以避免页面空白
						this.setDefaultUserInfo()
						
						uni.showToast({
							title: '网络连接失败',
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			
			// 设置默认用户信息（未登录或加载失败时）
			setDefaultUserInfo() {
				this.userInfo = {
					userId: null,
					nickname: '未登录用户',
					avatar: 'https://via.placeholder.com/100?text=未登录',
					phone: '',
					email: '',
					gender: null,
					genderText: '未知',
					birthDate: null,
					age: null,
					isVerified: false,
					profileProgress: 0,
					isVip: false,
					height: null,
					weight: null,
					star: null,
					animal: null,
					educationLevel: null,
					schoolName: null,
					company: null,
					jobTitle: null,
					salaryRange: null,
					maritalStatus: null,
					house: null,
					car: null,
					hobby: null,
					authenticityScore: 0
				}
				
				// 显示登录提示（仅在没有登录时显示）
				const token = uni.getStorageSync('token')
				if (!token) {
					setTimeout(() => {
						uni.showModal({
							title: '提示',
							content: '请先登录以查看完整功能',
							showCancel: true,
							cancelText: '稍后',
							confirmText: '去登录',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/page3/page3?redirect=' + encodeURIComponent('/pages/mine/index')
									})
								}
							}
						})
					}, 1000) // 延迟1秒显示，避免页面刚加载就弹窗
				}
			},
			
			// 加载签到信息
			loadCheckinInfo() {
				// 确保有用户ID
				if (!this.userInfo.userId) {
					console.error('用户ID不存在，无法加载签到信息')
					return
				}
				
				uni.request({
					url: this.gatewayURL + '/api/checkin/info',
					method: 'GET',
					data: {
						userId: this.userInfo.userId
					},
					success: (res) => {
						console.log('签到信息:', res.data)
						
						if (res.data.code === 200) {
							const data = res.data.data
							
							// 更新签到数据
							this.checkinData = {
								continuousDays: data.continuousDays,
								totalDays: data.totalDays,
								todayChecked: data.todayChecked,
								checkedDates: data.checkedDates
							}
							
							// 更新奖励列表
							this.checkinRewards = data.rewards
							
							// 生成日历
							this.generateCalendarFromBackend(data.checkedDates)
						}
					},
					fail: (err) => {
						console.error('获取签到信息失败:', err)
						uni.showToast({
							title: '加载签到信息失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 根据后端数据生成日历
			generateCalendarFromBackend(checkedDates) {
				const today = new Date()
				const year = today.getFullYear()
				const month = today.getMonth()
				const todayStr = this.formatDate(today) // 今天的日期字符串
				
				this.currentMonth = `${year}年${month + 1}月`
				const firstDay = new Date(year, month, 1).getDay()
				const daysInMonth = new Date(year, month + 1, 0).getDate()
				const days = []
				
				for (let i = 0; i < firstDay; i++) {
					days.push({ date: null, checked: false, isToday: false })
				}
				
				for (let i = 1; i <= daysInMonth; i++) {
					const date = new Date(year, month, i)
					const dateStr = this.formatDate(date)
					const isToday = dateStr === todayStr // 通过日期字符串比较，更准确
					const checked = checkedDates.includes(dateStr)
					
					days.push({
						date: i,
						checked: checked,
						isToday: isToday,
						dateStr: dateStr
					})
				}
				
				this.calendarDays = days
			},
			// 格式化日期
			formatDate(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			// 显示签到弹窗
			showCheckinPopup() {
				this.$refs.checkinPopup.open()
			},
			// 关闭签到弹窗
			closeCheckinPopup() {
				this.$refs.checkinPopup.close()
			},
			// 处理签到（通过网关）
			handleCheckin() {
				if (this.checkinData.todayChecked) {
					uni.showToast({
						title: '今日已签到',
						icon: 'none'
					})
					return
				}
				
				// 确保有用户ID
				if (!this.userInfo.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				// 调用后端签到接口（通过网关）
				uni.request({
					url: this.gatewayURL + '/api/checkin/sign?userId=' + this.userInfo.userId,
					method: 'POST',
					success: (res) => {
						console.log('签到结果:', res.data)
						
						if (res.data.code === 200) {
							// 显示签到成功提示
							uni.showToast({
								title: res.data.message,
								icon: 'success',
								duration: 2500
							})
							
							const data = res.data.data
							
							// 更新签到数据
							this.checkinData = {
								continuousDays: data.continuousDays,
								totalDays: data.totalDays,
								todayChecked: data.todayChecked,
								checkedDates: data.checkedDates
							}
							
							// 更新奖励列表
							this.checkinRewards = data.rewards
							
							// 重新生成日历
							this.generateCalendarFromBackend(data.checkedDates)
							
						} else {
							// 签到失败
							uni.showToast({
								title: res.data.message,
								icon: 'none',
								duration: 2000
							})
						}
					},
					fail: (err) => {
						console.error('签到失败:', err)
						uni.showToast({
							title: '签到失败，请稍后重试',
							icon: 'none'
						})
					}
				})
			},
			goVerify() {
				uni.showToast({
					title: '前往实名认证',
					icon: 'none'
				})
			},
			goCompleteProfile() {
				this.goToPage('basicInfo')
			},
			goVip() {
				uni.navigateTo({
					url: '/pages/vip/index'
				})
			},
			goToPage(page) {
				console.log('=== goToPage 被调用 ===')
				console.log('页面参数:', page)
				console.log('当前用户ID:', this.currentUserId)
				
				try {
					if (page === 'basicInfo') {
						console.log('✅ 跳转到基本资料页面')
						// 跳转到基本资料页面
						uni.navigateTo({
							url: '/pages/profile/index',
							success: () => {
								console.log('✅ 基本资料页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 基本资料页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'partTimeMatchmaker') {
						console.log('✅ 跳转到兼职红娘页面')
						// 跳转到兼职红娘页面
						uni.navigateTo({
							url: '/pages/part-time-matchmaker/index',
							success: () => {
								console.log('✅ 兼职红娘页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 兼职红娘页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'blacklist') {
						console.log('✅ 跳转到黑名单页面')
						// 跳转到黑名单页面
						uni.navigateTo({
							url: '/pages/blacklist/index',
							success: () => {
								console.log('✅ 黑名单页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 黑名单页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'partnerRequirement') {
						console.log('✅ 跳转到对象要求页面')
						// 跳转到对象要求页面
						uni.navigateTo({
							url: '/pages/partner-requirement/index',
							success: () => {
								console.log('✅ 对象要求页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 对象要求页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'settings') {
						console.log('✅ 跳转到设置页面')
						// 跳转到设置页面
						uni.navigateTo({
							url: '/pages/settings/index',
							success: () => {
								console.log('✅ 设置页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 设置页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'customize') {
						console.log('✅ 跳转到私人定制页面')
						// 跳转到私人定制页面
						uni.navigateTo({
							url: '/pages/customize/index',
							success: () => {
								console.log('✅ 私人定制页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 私人定制页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else if (page === 'matchmakers') {
						console.log('✅ 跳转到红娘服务页面')
						// 跳转到红娘服务页面
						uni.navigateTo({
							url: '/pages/matchmakers/list',
							success: () => {
								console.log('✅ 红娘服务页面跳转成功')
							},
							fail: (err) => {
								console.error('❌ 红娘服务页面跳转失败:', err)
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								})
							}
						})
					} else {
						console.log('⚠️ 未知页面类型:', page)
						uni.showToast({
							title: '功能开发中',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('❌ goToPage 执行出错:', error)
					uni.showToast({
						title: '页面跳转异常',
						icon: 'none'
					})
				}
			},
			switchTab(tab) {
				if (tab === 'mine') return
				
				const tabPages = {
					index: '/pages/index/index',
					plaza: '/pages/plaza/index',
					recommend: '/pages/recommend/index',
					message: '/pages/message/index'
				}
				
				if (tabPages[tab]) {
					uni.redirectTo({
						url: tabPages[tab]
					})
				}
			},
			
			// 处理退出登录
			handleLogout() {
				console.log('点击退出登录按钮')
				
				uni.showModal({
					title: '退出登录',
					content: '确定要退出登录吗？',
					showCancel: true,
					cancelText: '取消', 
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							console.log('用户确认退出登录')
							this.executeLogout()
						} else {
							console.log('用户取消退出登录')
						}
					}
				})
			},
			
			// 执行退出登录（最可靠的方式）
			executeLogout() {
				console.log('=== 执行退出登录 ===')
				
				// 立即显示加载状态
				uni.showLoading({
					title: '退出中...',
					mask: true
				})
				
				// 延迟执行，确保UI更新
				setTimeout(() => {
					try {
						console.log('步骤1: 清除登录数据')
						
						// 方法1: 逐个清除
						uni.removeStorageSync('token')
						uni.removeStorageSync('userInfo')
						uni.removeStorageSync('userId')
						uni.removeStorageSync('rememberedAccount')
						
						console.log('步骤2: 验证数据清除')
						const remainToken = uni.getStorageSync('token')
						const remainUser = uni.getStorageSync('userInfo')
						console.log('清除后检查 - token:', remainToken, 'userInfo:', remainUser)
						
						// 如果还有残留数据，使用强制清除
						if (remainToken || remainUser) {
							console.log('检测到残留数据，执行强制清除')
							uni.clearStorageSync()
						}
						
						console.log('步骤3: 重置页面状态')
						this.currentUserId = null
						this.userInfo = {
							userId: null,
							nickname: '未登录用户',
							avatar: 'https://via.placeholder.com/100?text=未登录'
						}
						
						// 隐藏加载，显示成功
						uni.hideLoading()
						uni.showToast({
							title: '退出成功！',
							icon: 'success',
							duration: 1500
						})
						
						// 延迟跳转
						setTimeout(() => {
							console.log('步骤4: 跳转到登录页面')
							uni.reLaunch({
								url: '/pages/page3/page3'
							})
						}, 1500)
						
					} catch (error) {
						console.error('退出过程出错:', error)
						uni.hideLoading()
						
						// 强制退出
						uni.clearStorageSync()
						uni.showModal({
							title: '退出完成',
							content: '已清除登录信息，请重新打开应用',
							showCancel: false,
							confirmText: '知道了'
						})
					}
				}, 300) // 300毫秒延迟确保UI响应
			},
			
			// 设置测试用户数据（基于数据库真实数据）
			// ⚠️ 已弃用：此方法仅供调试使用，正常流程不再调用测试数据
			setTestUserData() {
				console.log('=== 设置测试用户数据 ===')
				console.warn('⚠️ 警告：正在使用测试数据，这不应该在生产环境中发生')
				
				// 根据当前用户ID设置对应的数据库用户信息
				const userId = this.currentUserId || 1
				
				let userData = {}
				
				switch(userId) {
					case 1:
						userData = {
							userId: 1,
							nickname: '小明',
							avatar: 'https://example.com/avatar1.jpg',
							phone: '138****8001',
							email: 'user1@example.com',
							gender: 1,
							genderText: '男',
							birthDate: '1990-05-05',
							age: 34,
							isVerified: true,
							profileProgress: 80,
							isVip: false
						}
						break
					case 2:
						userData = {
							userId: 2,
							nickname: '小红',
							avatar: 'https://example.com/avatar2.jpg',
							phone: '138****8002',
							email: 'user2@example.com',
							gender: 2,
							genderText: '女',
							birthDate: '1992-08-22',
							age: 32,
							isVerified: true,
							profileProgress: 90,
							isVip: true
						}
						break
					case 3:
						userData = {
							userId: 3,
							nickname: '用户5718',
							avatar: 'https://via.placeholder.com/100?text=用户',
							phone: '188****5718',
							email: '',
							gender: 0,
							genderText: '未知',
							birthDate: null,
							age: null,
							isVerified: false,
							profileProgress: 30,
							isVip: false
						}
						break
					default:
						userData = {
							userId: userId,
							nickname: '测试用户',
							avatar: 'https://via.placeholder.com/100?text=测试',
							phone: '',
							email: '',
							gender: 0,
							genderText: '未知',
							birthDate: null,
							age: null,
							isVerified: false,
							profileProgress: 20,
							isVip: false
						}
				}
				
				// 设置用户信息
				this.userInfo = userData
				
				console.log('✅ 测试用户数据设置完成:', this.userInfo.nickname)
				
				// 设置统计数据
				this.stats = {
					myConnection: Math.floor(Math.random() * 10),
					myFavorites: Math.floor(Math.random() * 20),
					whoViewedMe: Math.floor(Math.random() * 15),
					iViewed: Math.floor(Math.random() * 25)
				}
				
				// 显示提示
				uni.showToast({
					title: '使用测试数据: ' + this.userInfo.nickname,
					icon: 'success',
					duration: 2000
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.mine-page {
		min-height: 100vh;
		background: linear-gradient(180deg, #FF8A9B 0%, #FFB4C0 30%, #F5F5F5 60%);
		padding-bottom: 120rpx;
	}

	/* 用户信息区域 */
	.user-section {
		margin: 30rpx;
		margin-top: env(safe-area-inset-top);
		padding-top: 0;
		
		.user-info {
			display: flex;
			align-items: flex-start;
			margin-bottom: 40rpx;
			
			.avatar {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
				margin-right: 25rpx;
				background-color: #FFFFFF;
				border: 4rpx solid #FFFFFF;
			}
			
			.user-details {
				flex: 1;
				
				.nickname-row {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					margin-top: 10rpx;
					
					.nickname {
						font-size: 38rpx;
						font-weight: bold;
						color: #333333;
						margin-right: 20rpx;
					}
					
					.verify-badge {
						background: linear-gradient(135deg, #B8E986 0%, #7FD957 100%);
						padding: 8rpx 20rpx;
						border-radius: 30rpx;
						
						.verify-text {
							font-size: 22rpx;
							color: #FFFFFF;
						}
					}
				}
				
				.progress-row {
					display: flex;
					align-items: center;
					
					.progress-bar {
						flex: 1;
						height: 16rpx;
						background-color: rgba(255, 255, 255, 0.5);
						border-radius: 8rpx;
						overflow: hidden;
						margin-right: 20rpx;
						
						.progress-fill {
							height: 100%;
							background: linear-gradient(90deg, #B8E986 0%, #7FD957 100%);
							border-radius: 8rpx;
							transition: width 0.3s;
						}
					}
					
					.progress-text {
						font-size: 24rpx;
						color: #666666;
						white-space: nowrap;
					}
				}
			}
		}
		
		.stats-row {
			display: flex;
			justify-content: space-around;
			
			.stat-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.stat-number {
					font-size: 44rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 10rpx;
				}
				
				.stat-label {
					font-size: 24rpx;
					color: #666666;
				}
			}
		}
	}

	/* VIP会员卡片 */
	.vip-card {
		margin: 30rpx;
		background: linear-gradient(135deg, #E8E5FF 0%, #D5CFFF 100%);
		border-radius: 20rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 4rpx 20rpx rgba(149, 117, 205, 0.15);
		
		.vip-content {
			display: flex;
			align-items: center;
			
			.vip-icon {
				font-size: 60rpx;
				margin-right: 20rpx;
			}
			
			.vip-info {
				display: flex;
				flex-direction: column;
				
				.vip-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #6B4EA3;
					margin-bottom: 8rpx;
				}
				
				.vip-subtitle {
					font-size: 24rpx;
					color: #8B7BAA;
				}
			}
		}
		
		.vip-button {
			background: linear-gradient(135deg, #9575CD 0%, #7E57C2 100%);
			color: #FFFFFF;
			padding: 16rpx 32rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			white-space: nowrap;
		}
	}

	/* 专属红娘 */
	.matchmaker-card {
		margin: 30rpx;
		margin-top: 20rpx;
		background: linear-gradient(135deg, #FFF8E1 0%, #FFE9B8 100%);
		border-radius: 16rpx;
		padding: 25rpx;
		text-align: center;
		
		.matchmaker-text {
			font-size: 26rpx;
			color: #F57C00;
		}
	}

	/* 快捷入口 */
	.quick-actions {
		margin: 30rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 40rpx;
		display: flex;
		justify-content: space-around;
		box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
		
		.action-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.action-icon {
				width: 100rpx;
				height: 100rpx;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 50rpx;
				margin-bottom: 15rpx;
			}
			
			.calendar-icon {
				background: linear-gradient(135deg, #FFE5E5 0%, #FFD0D0 100%);
			}
			
			.phone-icon {
				background: linear-gradient(135deg, #FFE8F5 0%, #FFD0EB 100%);
			}
			
			.heart-icon {
				background: linear-gradient(135deg, #FFE5E5 0%, #FFB8B8 100%);
			}
			
			.action-label {
				font-size: 26rpx;
				color: #666666;
			}
		}
	}

	/* 功能菜单列表 */
	.menu-list {
		margin: 30rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
		
		.menu-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 35rpx 30rpx;
			border-bottom: 1rpx solid #F5F5F5;
			
			&:last-child {
				border-bottom: none;
			}
			
			.menu-left {
				display: flex;
				align-items: center;
				
				.menu-icon {
					font-size: 44rpx;
					margin-right: 20rpx;
				}
				
				.menu-text {
					font-size: 30rpx;
					color: #333333;
				}
			}
			
			.menu-arrow {
				font-size: 50rpx;
				color: #CCCCCC;
				font-weight: 300;
			}
		}
		
		/* 退出登录特殊样式 */
		.menu-item.logout-item {
			border-top: 1rpx solid #FFE5E5;
			background: linear-gradient(135deg, #FFF5F5 0%, #FFEBEB 100%);
			
			.menu-left .menu-icon {
				color: #E74C3C;
			}
			
			.menu-left .menu-text {
				color: #E74C3C;
				font-weight: 500;
			}
			
			.menu-arrow {
				color: #E74C3C;
			}
			
			&:active {
				background: linear-gradient(135deg, #FFEBEB 0%, #FFE0E0 100%);
			}
		}
	}

	/* 签到弹窗样式 */
	.checkin-popup {
		width: 650rpx;
		max-height: 85vh;
		background-color: #FFFFFF;
		border-radius: 30rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		
		.popup-header {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 30rpx 30rpx 20rpx;
			position: relative;
			background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
			flex-shrink: 0;
			
			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			
			.close-btn {
				position: absolute;
				right: 20rpx;
				top: 25rpx;
				width: 50rpx;
				height: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.close-icon {
					font-size: 36rpx;
					color: #FFFFFF;
				}
			}
		}
		
		.checkin-info {
			display: flex;
			justify-content: space-around;
			padding: 20rpx 30rpx;
			background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
			flex-shrink: 0;
			
			.info-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.info-label {
					font-size: 22rpx;
					color: rgba(255, 255, 255, 0.8);
					margin-bottom: 8rpx;
				}
				
				.info-value {
					font-size: 36rpx;
					font-weight: bold;
					color: #FFFFFF;
				}
			}
		}
		
		.checkin-content {
			flex: 1;
			overflow-y: auto;
			max-height: 50vh;
		}
		
		.checkin-calendar {
			padding: 20rpx 30rpx;
			
			.calendar-header {
				text-align: center;
				margin-bottom: 15rpx;
				
				.month-text {
					font-size: 26rpx;
					font-weight: bold;
					color: #333333;
				}
			}
			
			.week-header {
				display: flex;
				margin-bottom: 10rpx;
				
				.week-day {
					flex: 1;
					text-align: center;
					font-size: 22rpx;
				color: #999999;
				}
			}
			
			.calendar-body {
				display: flex;
				flex-wrap: wrap;
				
				.calendar-day {
					width: calc(100% / 7);
					height: 70rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;
					margin-bottom: 8rpx;
					
					.day-num {
						font-size: 24rpx;
						color: #333333;
					}
					
					.check-mark {
						position: absolute;
						top: 3rpx;
						right: 3rpx;
						font-size: 18rpx;
						color: #FFFFFF;
						background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
						width: 26rpx;
						height: 26rpx;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
					}
					
					&.empty {
						visibility: hidden;
					}
					
					&.checked {
						background: linear-gradient(135deg, #FFE5EC 0%, #FFD0DC 100%);
						border-radius: 8rpx;
						
						.day-num {
							color: #FF8A9B;
							font-weight: bold;
						}
					}
					
					&.today {
						background: linear-gradient(135deg, #FF8A9B 0%, #FFB4C0 100%);
						border-radius: 8rpx;
						
						.day-num {
							color: #FFFFFF;
							font-weight: bold;
						}
					}
					
					&.today.checked {
						.check-mark {
							background: #FFFFFF;
							color: #FF8A9B;
						}
					}
				}
			}
		}
		
		.checkin-rewards {
			padding: 15rpx 30rpx 20rpx;
			border-top: 1rpx solid #F5F5F5;
			flex-shrink: 0;
			
			.rewards-title {
				font-size: 26rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 15rpx;
				display: block;
			}
			
			.rewards-list {
				display: flex;
				justify-content: space-between;
				gap: 15rpx;
				
				.reward-item {
					flex: 1;
					background: linear-gradient(135deg, #F8F8F8 0%, #F0F0F0 100%);
					border-radius: 15rpx;
					padding: 20rpx 12rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					position: relative;
					border: 2rpx solid transparent;
					
					.reward-icon {
						font-size: 50rpx;
						margin-bottom: 10rpx;
					}
					
					.reward-day {
						font-size: 24rpx;
						color: #666666;
						margin-bottom: 8rpx;
					}
					
					.reward-text {
						font-size: 26rpx;
						color: #333333;
						font-weight: bold;
					}
					
					.received-mark {
						position: absolute;
						top: 8rpx;
						right: 8rpx;
						width: 32rpx;
						height: 32rpx;
						background: linear-gradient(135deg, #B8E986 0%, #7FD957 100%);
						color: #FFFFFF;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 20rpx;
					}
					
					&.received {
						opacity: 0.6;
					}
					
					&.current {
						border-color: #FF8A9B;
						background: linear-gradient(135deg, #FFE5EC 0%, #FFD0DC 100%);
						box-shadow: 0 4rpx 15rpx rgba(255, 138, 155, 0.3);
						
						.reward-text {
							color: #FF8A9B;
						}
					}
				}
			}
		}
		
		.checkin-button-wrapper {
			padding: 0 30rpx 25rpx;
			flex-shrink: 0;
			
			.checkin-btn {
				width: 100%;
				background: linear-gradient(135deg, #FF8A9B 0%, #FF6B8A 100%);
				color: #FFFFFF;
				font-size: 30rpx;
				font-weight: bold;
				border-radius: 50rpx;
				padding: 20rpx;
				border: none;
				box-shadow: 0 8rpx 20rpx rgba(255, 107, 138, 0.3);
				
				&.disabled {
					background: linear-gradient(135deg, #CCCCCC 0%, #AAAAAA 100%);
					box-shadow: none;
				}
				
				&::after {
					border: none;
				}
			}
		}
	}
	
	/* 底部导航栏 */
	.tabbar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		background-color: #FFFFFF;
		border-top: 1rpx solid #F0F0F0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 999;

		.tabbar-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 15rpx 0;

			.tabbar-icon {
				font-size: 44rpx;
				margin-bottom: 5rpx;
			}

			.tabbar-text {
				font-size: 22rpx;
				color: #666666;
			}

			&.active {
				.tabbar-text {
					color: #FF8A9B;
					font-weight: bold;
				}
			}
		}
	}
</style>

